package cn.umbrella.crm_core.workbench.controller;

import cn.umbrella.crm_core.commons.contants.CONTANTS_CODE;
import cn.umbrella.crm_core.commons.domain.ResponseResult;
import cn.umbrella.crm_core.commons.listeners.ActivityReadListener;
import cn.umbrella.crm_core.commons.utils.DateUtils;
import cn.umbrella.crm_core.commons.utils.ExcelTools;
import cn.umbrella.crm_core.commons.utils.UUIDGenerator;
import cn.umbrella.crm_core.settings.domain.User;
import cn.umbrella.crm_core.settings.service.UserService;
import cn.umbrella.crm_core.workbench.domain.ActivitiesRemark;
import cn.umbrella.crm_core.workbench.domain.Activity;
import cn.umbrella.crm_core.workbench.service.ActivityRemarkService;
import cn.umbrella.crm_core.workbench.service.ActivityService;
import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 市场活动
 */
@Controller
public class WorkbenchActivityController {

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

	@Autowired
	private ActivityRemarkService activityRemarkService;

    /**
     * 用户点击市场活动按钮，跳转市场活动页面
     * 
     * @return ModelAndView
     */
    @RequestMapping("/workbench/activity/index.do")
    public ModelAndView activityGO() {
        return new ModelAndView("workbench/activity/index");
    }

    /**
     * 请求返回已有用户名称列表
     * 
     * @return 返回用户列表
     */
    @RequestMapping("/workbench/activity/getUsersName.do")
    @ResponseBody
    public List<User> getAllUsersName() {
	List<User> usersName = new ArrayList<User>();
	usersName = userService.queryAllUserInfo();
	return usersName;
    }

    /**
     * 创建新的市场活动信息
     * 
     * @param activity
     * @param session
     * @return
     */
    @RequestMapping("/workbench/activity/createActivity.do")
    @ResponseBody
    public Object createNewActivityController(Activity activity, HttpSession session) {
	// 添加ID
	activity.setId(UUIDGenerator.generateUUID());
	// 添加创建时间
	activity.setCreateTime(DateUtils.dateToString(new Date()));
	// 添加创建人
	User user = (User) session.getAttribute(CONTANTS_CODE.SESSION_USER);
	if (user != null) {
	    activity.setCreateBy(user.getId());
	}
	// 创建返回消息对象
	ResponseResult responseResult = new ResponseResult();
	try {
	    int ret = activityService.createNewActivity(activity);
	    if (ret > 0) {
		responseResult.setCode("1");
	    } else {
		responseResult.setCode("0");
		responseResult.setMessage("系统繁忙，请稍后再试");
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	    responseResult.setCode("0");
	    responseResult.setMessage("系统繁忙，请稍后再试");
	}
	return responseResult;

    }
    
    /**
     * 处理市场活动查询请求
     * @param name
     * @param owner
     * @param startDate
     * @param endDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping("/workbench/activity/showActivityListByCondition.do")
    @ResponseBody
    public Object showActivityListByCondition(String name, String owner, String startDate, String endDate, int pageNo, int pageSize) {
	Map<String,Object> conditions = new HashMap<>();
	conditions.put("name", name);
	conditions.put("owner", owner);
	conditions.put("startDate", startDate);
	conditions.put("endDate", endDate);
	conditions.put("beginNo", (pageNo-1)*pageSize);
	conditions.put("pageSize", pageSize);
	List<Activity> activityList = activityService.queryActivityByConditionsForPage(conditions);
	int activityCount = activityService.queryActivityCountsByConditions(conditions);
	Map<String,Object> responseMap = new HashMap<>();
	responseMap.put("activityList", activityList);
	responseMap.put("activityCount", activityCount);
	return responseMap;
    }

	/**
	 *
	 * @param ids 从前端传过来的要删除的市场活动ID数组
	 * @return 执行结果对象，包含状态码及信息
	 */
	@RequestMapping("/workbench/activity/deleteActivitiesByIdArray.do")
	@ResponseBody
	public Object deleteActivitiesByIdArray(@RequestBody ArrayList<String> ids){
		System.out.println(ids);
		ResponseResult responseResult = new ResponseResult();

		try{
			if(ids == null || ids.isEmpty()){
				responseResult.setCode(CONTANTS_CODE.FAIL);
				responseResult.setMessage("您发送的删除请求有误，请检查！");
				return responseResult;
			}
			int haveDeletedRows = activityService.deleteActivities(ids);
			if(haveDeletedRows>0){
				responseResult.setCode(CONTANTS_CODE.SUCCESS);
			}else{
				responseResult.setCode(CONTANTS_CODE.FAIL);
				responseResult.setMessage("删除失败！");
			}
		}catch (Exception e){
			e.printStackTrace();
			responseResult.setCode(CONTANTS_CODE.FAIL);
			responseResult.setMessage("出错啦！");
		}
		return responseResult;
	}

	/**
	 * 用户发送请求，传递市场活动的ID过来
	 * @param id 市场活动的ID
	 * @return 返回一个结果对象，将查询结果信息及查询到的市场活动对象一并返回
	 */
	@RequestMapping("/workbench/activity/querySingleActivityById.do")
	@ResponseBody
	public Object querySingleActivityById(String id){
		ResponseResult responseResult = new ResponseResult();
		if(id == null || id.isEmpty()){
			responseResult.setCode(CONTANTS_CODE.FAIL);
			responseResult.setMessage("请停止发送恶意请求");
			return responseResult;
		}
		Activity activity = activityService.queryActivityById(id);
		responseResult.setCode(CONTANTS_CODE.SUCCESS);
		responseResult.setOthers(activity);
		return responseResult;
	}

	/**
	 * 修改市场活动
	 * @param activity 用户选中并将改市场活动传到后台
	 * @param session Session
	 * @return 返回修改的结果
	 */
	@RequestMapping("/workbench/activity/modifyActivityById.do")
	@ResponseBody
	public Object modifyActivityById(Activity activity, HttpSession session){
		ResponseResult responseResult = new ResponseResult();
		// 定义修改人及修改时间
		User user = (User) session.getAttribute(CONTANTS_CODE.SESSION_USER);
		activity.setEditBy(user.getId());
		activity.setEditTime(DateUtils.dateToString(new Date()));
		// 调用service执行修改操作
		try{
			int stateCode = activityService.modifyActivity(activity);
			if(stateCode>0){
				responseResult.setCode(CONTANTS_CODE.SUCCESS);
			}else{
				responseResult.setCode(CONTANTS_CODE.FAIL);
				responseResult.setMessage("修改市场活动失败，请重试！");
			}
		}catch (Exception e){
			e.printStackTrace();
			responseResult.setCode(CONTANTS_CODE.FAIL);
			responseResult.setMessage("系统繁忙，请稍候再试！");
		}
		return responseResult;
	}

	/**
	 * 导出所有的市场活动
	 * @param response 使用了EasyExcel的写Excel功能，将Excel写出到流中
	 */
	@RequestMapping("/workbench/activity/downloadAllActivity.do")
	public void downloadAllActivity(HttpServletResponse response) {
		// 定义对象列表
		List<Activity> list = new ArrayList<>();
		list = activityService.queryAllActivities();
		ExcelTools.writeActivities2Web(response,list,"导出所有市场活动");
	}

	/**
	 * 导出用户选中的市场活动
	 * @param response 使用了EasyExcel的写Excel功能，将Excel写出到流中
	 * @param id 需要前端传进来用户选中的市场活动ID
	 */
	@RequestMapping("/workbench/activity/downloadSelectedActivities.do")
	public void downloadSelectedActivities(HttpServletResponse response, String[] id) {
		// 定义对象列表
		List<Activity> list = new ArrayList<>();
		list = activityService.queryActivitiesByIds(id);
		ExcelTools.writeActivities2Web(response, list,"导出选中的市场活动列表");
	}

	/**
	 * 测试文件上传
	 * @param file 接收文件
	 * @param userName 用户姓名
	 * @return 返回结果
	 * @throws IOException 抛出异常
	 */
	@RequestMapping("/workbench/activity/fileUpload.do")
	@ResponseBody
	public Object fileUpload(@RequestParam("myFile") MultipartFile file, String userName) throws IOException {
		ResponseResult rs = new ResponseResult();
		System.out.println("userName:"+userName);

		if(file == null){

			System.out.println("啥都没收到！");
			rs.setCode(CONTANTS_CODE.FAIL);
			rs.setMessage("上传失败");
			return rs;
		}
		String fileName = file.getOriginalFilename();
		System.out.println("fileName:"+fileName);
		File saveFilePath = new File("C:\\Users\\Aerle\\Desktop\\",fileName);
		file.transferTo(saveFilePath);
		rs.setCode(CONTANTS_CODE.SUCCESS);
		rs.setMessage("收到了上传的文件");
		return rs;
	}

	/**
	 * 导入市场活动
	 * @param session 用于获取当前用户
	 * @param file 文件
	 * @return 返回结果
	 */
	@RequestMapping("/workbench/activity/importActivities.do")
	@ResponseBody
	public Object importActivities(HttpSession session,@RequestParam("ActivitiesFile") MultipartFile file){
		System.out.println("请求成功！");
		ResponseResult rs = new ResponseResult();
		User currentUser = (User)session.getAttribute(CONTANTS_CODE.SESSION_USER);
		String currentUserID = currentUser.getId();
		if(file == null){
			rs.setCode(CONTANTS_CODE.FAIL);
			rs.setMessage("上传失败，请稍候重试！");
		}else {
			try {
				EasyExcel.read(file.getInputStream(), Activity.class, new ActivityReadListener(activityService, currentUserID)).sheet().doRead();
				rs.setCode(CONTANTS_CODE.SUCCESS);
				rs.setMessage("上传成功");
			} catch (IOException e) {
				e.printStackTrace();
				rs.setCode(CONTANTS_CODE.FAIL);
				rs.setMessage(e.getMessage());
			}
		}
        return rs;
	}

	/**
	 * 下载市场活动导入的模板文件
	 * @param response 直接返回文件
	 */
	@RequestMapping("/workbench/activity/downloadActivityTemplate.do")
	public void downloadActivityTemplate(HttpServletResponse response){
		String fileName = "市场活动导入模板.xlsx";
		String filePath = "templates/" + fileName;

		try (InputStream inputStream = new ClassPathResource(filePath).getInputStream();
			 OutputStream outputStream = response.getOutputStream()) {
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
			IOUtils.copy(inputStream, outputStream);
			// 可以在这里记录成功下载的日志
		} catch (IOException e) {
			// 记录异常日志并处理异常，可以考虑转换为自定义的异常类并向上抛出
			e.printStackTrace();
		}
	}

	/**
	 * 跳转到市场活动详情页面
	 * @param activityId 前端传递的市场活动ID
	 * @return 跳转页面，携带ID
	 */
	@RequestMapping("/workbench/activity/activityDetail.do")
	public ModelAndView activityDetail(String activityId){
		ModelAndView modelAndView = new ModelAndView();
		if(activityId == null || activityId.isEmpty()){
			return null;
		}
		modelAndView.setViewName("workbench/activity/detail");
        return modelAndView;
		// 重定向到静态HTML页面，并带上activityId参数
		//return "redirect:detail.html?activityId=" + activityId;
	}

	/**
	 * 前端页面发送ajax请求，返回ID对应的市场活动详情
	 * @param activityId 前端传递市场活动ID过来
	 * @return 返回结果对象
	 */
	@RequestMapping("/workbench/activity/activityDetailShow.do")
	@ResponseBody
	public Object activityDetailShow(String activityId){
		ResponseResult rs = new ResponseResult();
		Map<String,Object> details = new HashMap<String,Object>();
		if(activityId == null || activityId.isEmpty()){
			rs.setCode(CONTANTS_CODE.FAIL);
			rs.setMessage("请求有误，请稍候重试");
			return rs;
		}
		try {
			Activity currentActivity = activityService.queryActivityForDetails(activityId);
			List<ActivitiesRemark> activitiesRemarks = activityRemarkService.getActivitiesRemarkByActivityId(activityId);
			details.put("activity", currentActivity);
			details.put("activitiesRemarks", activitiesRemarks);
			rs.setCode(CONTANTS_CODE.SUCCESS);
			rs.setOthers(details);
		}catch (Exception e){
			rs.setCode(CONTANTS_CODE.FAIL);
			rs.setMessage(e.getMessage());
		}
		return rs;
	}


}
